/**
 * @description 更新订单状态(入参只能传1，2，3，4.其他状态无效)
 * @author unhejing (成都-敬宇杰)
 * @date 2020-02-26 下午5:37:46
 */
const {
  validateToken
} = require('../../utils/validateToken.js')
'use strict';
const db = uniCloud.database()
const statusEnum = ['待付款','已取消','货到付款','已支付','已完成']
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event:' + event)
	//event.token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuaWQiOiJvbHVYcjRsMFVrRnlTN3BoZ2JrUE92akR2UWJnIn0.gmAEd_I2AktSoElvsfWzpCVKlXlxE4wChweOD2Jqt4k"
	let tokenRes = await validateToken(event.token)
	if(tokenRes.code != 0){
		return tokenRes;
	}
	event.user_id = tokenRes.user_id;
	// event.user_id = "1";
	// event.status = 2;//订单状态
	if (event.user_id == '' || !event.user_id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少用户id'
		}
	}
	if (event.id == '' || !event.id) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少订单id'
		}
	}
	if (event.status == '' || !event.status) {
		return {
			success: false,
			code: -1,
			msg: '参数错误，缺少订单状态status'
		}
	}
	event.status = parseInt(event.status)
	let effectiveStatus = [1,2,3,4]
	if (!effectiveStatus.includes(event.status)) {
		return {
			success: false,
			code: -1,
			msg: '订单状态无效'
		}
	}
	const collection = db.collection('order') // 获取表'order'的集合对象
	let res = await collection.doc(event.id).get();
	console.log("订单响应数据:" + JSON.stringify(res))
	
	if (!res.data || res.data.length < 1) {
		return {
			success: false,
			code: -1,
			msg: '获取订单失败'
		}
	}
	let orderInfo = res.data[0];
	let currentStatus = orderInfo.status;
	if(event.status == 1 && currentStatus != 0){
		return {
			success: false,
			code: -1,
			msg: '当前订单状态为：'+statusEnum[currentStatus]+',无法取消'
		}
	}
	if(event.status == 2  && currentStatus != 0){
		return {
			success: false,
			code: -1,
			msg: '当前订单状态为：'+statusEnum[currentStatus]+',无法货到付款'
		}
	}
	if(event.status == 3  && currentStatus != 0){
		return {
			success: false,
			code: -1,
			msg: '当前订单状态为：'+statusEnum[currentStatus]+',无法变更为已支付'
		}
	}
	if(event.status == 4  && currentStatus != 2 && currentStatus != 3){
		return {
			success: false,
			code: -1,
			msg: '当前订单状态为：'+statusEnum[currentStatus]+',无法变更为已完成'
		}
	}
	
	let orderData = await collection.doc(event.id).update({
		status: event.status
	})
	console.log("更改订单状态响应内容："+JSON.stringify(orderData))
	if(orderData.affectedDocs > 0){
		return {
			success: true,
			code: 0,
			msg: '更新状态成功'
		}
	}
	return {
		success: false,
		code: -1,
		msg: '服务器内部错误'
	}

};



